package com.mingke.java.task;

import com.mingke.java.params.BackupReturnValue;
import com.mingke.java.params.OperationBaseParams;
import com.mingke.java.utils.DataSourceUtils;

import java.sql.SQLException;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 插入任务，主要实现数据插入功能
 */
public class InsertTask implements Task{

    private static final ReentrantLock lock = new ReentrantLock();

    private BackupReturnValue value;

    private OperationBaseParams params;

    private Integer index;

    private Integer max;

    /**
     * 多线程同时操作一个ResultSet会出错
     * @return
     */
    @Override
    public String doTask() {
        long realBegin = System.currentTimeMillis();
        long begin = System.currentTimeMillis();
        long end = 1L;
        DataSourceUtils targetUtils = new DataSourceUtils();
        targetUtils.initSimpleConnection(params.getTargetDBURL(), params.getTargetUser(), params.getTargetPassword());

        targetUtils.initBatchExecutor(value.getInsertRawSQL());
        try {
            //遍历数据
            lock.lock();
            while(index < max) {
                //填充参数
                targetUtils.fillBatchSQLParams(getObjs(value, index));

                //执行批量代码
                if(index % DataSourceUtils.fetchSize == 0) {
                    lock.unlock();
                    targetUtils.doBatchSQL();
                    lock.lock();
                }
                index++;
            }
            //System.out.println("FetchSize: "+value.getResultSet().getFetchSize());
        } catch (Exception e) {
            e.printStackTrace();
        }
        lock.unlock();
        targetUtils.doBatchSQL();

        //关闭资源
        targetUtils.close();
        end = System.currentTimeMillis();
        return "程序执行时间"+(end-realBegin)+"ms";
    }

    public InsertTask(BackupReturnValue value, OperationBaseParams params, Integer index, Integer max) {
        this.value = value;
        this.params = params;
        this.index = index;
        this.max = max;
    }

    Object[] getObjs(BackupReturnValue value, int index) {
        Object objs[] = new Object[value.getColumnNum()];
        try {
            //手动拨一下光标
            value.getResultSet().absolute(index);
            //将列值取出直接放到Object数组中
            for (int i = 1; i <= value.getColumnNum(); i++) {
                objs[i-1] = value.getResultSet().getObject(i);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return objs;
    }
}
